package cn.dakaqi.open.auth;

import cn.dakaqi.annotation.Login;
import cn.dakaqi.exception.LoginRequiredException;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private RedisClientTemplate redisClientTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Login login = handlerMethod.getMethodAnnotation(Login.class);
            if (null == login) {
                return true;
            }
            String token = null;
            Cookie cookies[] = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName() != null) {
                        if (cookie.getName().equals("token") && cookie.getValue() != null) {
                            token = cookie.getValue().trim();
                        }
                    }

                }
            }

            if (StringUtils.isEmpty(token)) {
                token = request.getHeader("token");
            }
            // Did not login yet
            if (null == token || StringUtils.isEmpty(token.trim())) {
                throw new LoginRequiredException("Login", "exception.user.notLogin");
            } else {
                HttpSession session = request.getSession();
                if (session.getAttribute("userId") != null) {
                    String userId = session.getAttribute("userId").toString();

                    String redisToken = redisClientTemplate.hget("login", userId);

                    if (!token.equalsIgnoreCase(redisToken)) {
                        throw new LoginRequiredException("Login", "exception.user.notLogin");
                    }
                } else {
                    throw new LoginRequiredException("Login", "exception.user.notLogin");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        preHandle(request, response, handler);
    }
}